package com.shuo.dsa.niuke;

/**
 * 请实现一个函数，将一个字符串中的每个空格替换成“%20”。例如，
 * 当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy
 */
public class ReplaceSpace {
    public String replaceSpace(StringBuffer str) {
        String s = str.toString();
        char[] c = s.toCharArray();
        int spaceNum = 0;
        for (char c1 : c) {
            if (c1 == ' ')
                spaceNum++;
        }
        char[] ret = new char[c.length + spaceNum * 2];
        int j = ret.length - 1;
        for (int i = c.length - 1; i >= 0; i--) {
            if (c[i] != ' ') {
                ret[j] = c[i];
                j--;
            } else {
                ret[j] = '0';
                j--;
                ret[j] = '2';
                j--;
                ret[j] = '%';
                j--;
            }
        }
        return new String(ret);
    }

    public static void main(String[] args) {
        System.out.println(new ReplaceSpace().replaceSpace(new StringBuffer("hello world")));
    }
}
